<?php
namespace app\logic\yuql;

use app\api\model\yuql\Purchase;
use app\api\model\yuql\Search;
use app\api\model\yuql\Order;
use app\api\model\yuql\OrderLog;
use app\api\model\yuql\Seckill;
use app\services\yuql\FiltraServices;
use app\services\yuql\RedisServices;
use app\validate\yuql\GoodsValidate;

class SeckillLogic
{

    /**
     * yuql
     * 商品展示逻辑
     * @return Seckill[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function goodsListLogic($params)
    {

        //用户搜索同时存入搜索记录
        if (!empty($params['keyword']) || isset($params['keyword'])){
            $searchGoods = Seckill::userSearchGoods($params['keyword']);
            if (empty($searchGoods)) throw new \Exception('抱歉，没有此类商品');
            $historyOne = Search::HistoryOne(['search_history'=>$params['keyword']]);
            if (empty($historyOne)){
                Search::HistorySet(['uid'=>$params['uid'],'search_history'=>$params['keyword']]);
            }else{
                Search::HistorySave(['uid'=>$params['uid'],'search_history'=>$params['keyword']]);
            }
            $data = Seckill::goodsListModel($params['keyword']);
        }else{
            $data = Seckill::goodsListModels();
        }
        if (!$data) throw new \Exception('数据获取失败');
        //优先展示推荐数据
        $recommendGoodsAll = HistoryLogic::getUserBehavior($params['uid']);
        return $recommendGoodsAll;
    }

    /**
     * yuql
     * 商品添加逻辑
     * 敏感词过滤
     * redis缓存同步入库
     * @param $params
     * @return Seckill|\think\Model
     * @throws \Exception
     */
    public static function goodsAddLogic($params)
    {
        validate(GoodsValidate::class)->check($params);
        //敏感词过滤
        $Filtra = FiltraServices::filte_test($params['title']);
        if ($Filtra['conclusion'] == '不合规') throw new \Exception('存在低俗辱骂不合规');
        $result = Seckill::goodsAddModel([
            'title' => $params['title'],
            'price' => $params['price'],
            'goods_id' => $params['goods_id'],
            'goods_num' => $params['goods_num'],
        ]);
        if (!$result) throw new \Exception('商品添加失败');
        $goods_id = $result['goods_id'];
        $num = $result['goods_num'];
        $redis = RedisServices::getInstance()->getRedis();
        $redis->select(2);
        for ($i = 0; $i < $num; $i++) {
            $redis->lPush($goods_id, $i);
        }
        return $result;
    }

    /**
     * yuql
     * 商品详情
     * @param $id
     * @return Seckill|array|mixed|\think\Model|null
     * @throws \Exception
     */
    public static function goodsDetailLogic($id)
    {
        if (!$id) throw new \Exception('商品不存在');
        $result = Seckill::goodsDetailOne(['goods_id' => $id]);
        return $result;
    }

    /**
     * yuql
     * redis缓存减 1
     * 修改 mysql库存
     * @param $params
     * @return Seckill|array|mixed|\think\Model
     * @throws \Exception
     */
    public static function goodsBuyLogic($params)
    {
        $goodsDetailOne = Seckill::goodsDetailOne(['goods_id' => $params['goods_id']]);
        if (!$goodsDetailOne) throw new \Exception('无此商品');

        $uid = $params['user_id'];
        $user_phone = $params['user_phone'];
        $goods_id = $goodsDetailOne['goods_id'];
        $goods_price = $goodsDetailOne['price'];
        $order_id = 'YQL' . mt_rand(10000, 99999);
        $goodsOrderSetLogic = SeckillLogic::goodsOrderSetLogic($uid, $user_phone, $goods_id, $goods_price, $order_id);
        if (!$goodsOrderSetLogic) throw new \Exception('订单生成失败');

        $redis = RedisServices::getInstance()->getRedis();
        $redis->select(2);
        $key = $goodsDetailOne['goods_id'];
        if ($redis->lLen($key) <= 0) throw new \Exception('秒杀失败，没有库存');
        $endNum = $redis->lPop($key);
        $result = Seckill::goodsNumUpdate($endNum, ['goods_id' => $key]);
        if (!$result) throw new \Exception('库存修改失败');
        return $result;
    }

    /**
     * yuql
     * 生成订单 ,存入日志
     * @param $uid
     * @param $user_phone
     * @param $goods_id
     * @param $goods_price
     * @param $order_id
     * @throws \Exception
     */
    public static function goodsOrderSetLogic($uid, $user_phone, $goods_id, $goods_price, $order_id)
    {
        $goodsOrderAdd = Order::goodsOrderAdd([
            'uid' => $uid,
            'user_phone' => $user_phone,
            'goods_id' => $goods_id,
            'order_id' => $order_id,
            'goods_price' => $goods_price,
        ]);
        if (!$goodsOrderAdd) throw new \Exception('订单生成失败');
        //生成订单同时存入用户购买记录
        $historyOne = Purchase::HistoryOne(['purchase_history'=>$goods_id]);
        if (empty($historyOne)){
            Purchase::HistorySet(['uid'=>$uid,'purchase_history'=>$goods_id]);
        }else{
            Purchase::HistorySave(['uid'=>$uid,'purchase_history'=>$goods_id]);
        }

        $goodsOrderLogAdd = OrderLog::goodsOrderLogAdd([
            'order_id' => $order_id,
            'user_phone' => $user_phone,
            'logcont' => '商品订单' . $uid . '日志生成',
            'create_time' => date('Y-m-d H:i:s')
        ]);
        if (!$goodsOrderLogAdd) throw new \Exception('日志存储失败');
        return $goodsOrderAdd;
    }
}